<template>
  <div class="sign-management-container">
    <!-- 顶部信息栏 -->
    <div class="top-info-bar">
      <div class="class-info">
        <span class="info-item">培训班编号：{{ trainingClassCode }}</span>
        <span class="splitter">|</span>
        <span class="info-item">培训班名称：{{ className }}</span>
      </div>
    </div>

    <!-- 操作按钮区 -->
    <div class="operation-buttons">
      <el-button type="primary" plain @click="handleExport">
        <i class="el-icon-download"></i> 导出
      </el-button>
      <el-button type="primary" plain @click="handleAddSignRecord">
        <i class="el-icon-plus"></i> 添加签到
      </el-button>
      <el-button type="primary" plain @click="showBatchQrcode" :disabled="!hasSelection">
        <i class="el-icon-qrcode"></i> 签到二维码
      </el-button>
      <el-button type="primary" plain @click="handlePrintQrcode" :disabled="!hasSelection">
        <i class="el-icon-printer"></i> 打印二维码
      </el-button>
      <el-button type="primary" plain @click="handleBatchDelete" :disabled="!hasSelection">
        <i class="el-icon-delete"></i> 批量删除
      </el-button>
      <el-button type="primary" plain @click="attendanceTracking" :disabled="!hasSelection">
        <i class="el-icon-eye"></i> 签到统计
      </el-button>
      <el-button type="primary" plain @click="res">
        <i class="el-icon-eye"></i> 刷新
      </el-button>
    </div>

    <!-- 签到记录表格 -->
    <el-table
      :data="signRecords"
      @selection-change="handleSelectionChange"
      border
      stripe
      size="mini"
      class="sign-records-table"
    >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <!-- <el-table-column prop="id" label="序号" width="80" align="center"></el-table-column> -->
      <el-table-column label="签到日期" align="center" min-width="200">
        <template #default="scope">
          <el-date-picker
            v-model="scope.row.checkinTime"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
            :disabled="!scope.row.editable"
            @change="handleDateChange(scope.row)"
            style="width:150px"
          ></el-date-picker>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" min-width="200">
        <template #default="scope">
          <el-time-picker
            v-model="scope.row.startTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择开始时间"
            :disabled="!scope.row.editable"
            @change="handleTimeChange(scope.row)"
            style="width:150px"
          ></el-time-picker>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" min-width="200">
        <template #default="scope">
          <el-time-picker
            v-model="scope.row.endTime"
            format="HH:mm:ss"
            value-format="HH:mm:ss"
            placeholder="选择结束时间"
            :disabled="!scope.row.editable"
            @change="handleTimeChange(scope.row)"
            style="width:150px"
          ></el-time-picker>
        </template>
      </el-table-column>
      <!-- 培训内容下拉框（绑定培训计划ID） -->
      <el-table-column label="培训内容" align="center" min-width="150">
        <template #default="scope">
          <el-select
            v-model="scope.row.trainingScheduleId"
            placeholder="请选择培训计划"
            :disabled="!scope.row.editable || scheduleList.length === 0"
            size="mini"
            style="width: 100%"
          >
            <el-option
              v-for="item in scheduleList"
              :key="item.trainingScheduleId"
              :label="item.trainingContent"
              :value="item.trainingScheduleId"
            ></el-option>
            <el-option v-if="scheduleList.length === 0" value="" disabled>
              暂无培训计划可选
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="签到地点" align="center" min-width="150">
        <template #default="scope">
          <el-input
            v-model="scope.row.checkinLocation"
            placeholder="请输入签到地点"
            :disabled="!scope.row.editable"
            size="mini"
          ></el-input>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === '已结束' ? 'success' : 'info'">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="280" fixed="right">
        <template #default="scope">
          <el-button
            type="text"
            size="mini"
            @click="showSingleQrcode(scope.row.id)"
            class="operation-btn"
          >
            <i class="el-icon-qrcode"></i> 签到二维码
          </el-button>
          <template v-if="!scope.row.editable">
            <el-button
              type="text"
              size="mini"
              @click="enterEditMode(scope.row)"
              class="operation-btn"
            >
              <i class="el-icon-edit"></i> 编辑
            </el-button>
          </template>
          <template v-if="scope.row.editable">
            <el-button
              type="text"
              size="mini"
              @click="saveSignRecord(scope.row)"
              class="operation-btn success"
            >
              <i class="el-icon-check"></i> 保存
            </el-button>
          </template>
          <el-button
            type="text"
            size="mini"
            @click="attendanceRecord(scope.row)"
            class="operation-btn"
          >
            <i class="el-icon-list"></i> 签到详情
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="deleteSignRecord(scope.row.id)"
            class="operation-btn danger"
          >
            <i class="el-icon-delete"></i> 删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增一行按钮 -->
    <div class="add-row-btn">
      <el-button type="primary" plain size="mini" @click="addEmptyRow">
        <i class="el-icon-plus"></i> 增加一行
      </el-button>
    </div>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="pagination.currentPage"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="pagination.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pagination.total"
      size="mini"
      class="pagination"
    ></el-pagination>

    <!-- 二维码弹窗 -->
    <el-dialog
      :title="qrcodeTitle"
      :visible.sync="qrcodeVisible"
      width="350px"
      center
    >
      <div class="qrcode-content">
        <div class="qrcode-wrapper">
          <img
            :src="qrcodeUrl"
            alt="签到二维码"
            class="qrcode-img"
            @error="handleQrcodeError"
          >
          <div v-if="qrcodeError" class="qrcode-error">
            二维码加载失败，请重试
          </div>
        </div>
        <div class="qrcode-info" v-if="currentSignRecord">
          <p><strong>签到日期：</strong>{{ currentSignRecord.checkinTime }}</p>
          <p><strong>签到时间：</strong>{{ currentSignRecord.startTime }} - {{ currentSignRecord.endTime }}</p>
          <p><strong>培训内容：</strong>{{ getTrainingContent(currentSignRecord.trainingScheduleId) }}</p>
          <p><strong>签到地点：</strong>{{ currentSignRecord.checkinLocation }}</p>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="qrcodeVisible = false">关闭</el-button>
          <el-button type="primary" @click="printCurrentQrcode">打印</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 签到结果弹窗 -->
    <el-dialog
      title="签到结果详情"
      :visible.sync="resultVisible"
      width="70%"
    >
      <div class="result-content" v-if="currentSignResult">
        <div class="result-header">
          <h3>{{ getTrainingContent(currentSignResult.trainingScheduleId) }}</h3>
          <p>
            <span>签到日期：{{ currentSignResult.date }}</span>
            <span>签到时间：{{ currentSignResult.timeRange }}</span>
            <span>应到人数：{{ currentSignResult.total }}</span>
            <span>实到人数：{{ currentSignResult.attended }}</span>
            <span>签到率：{{ currentSignResult.rate }}%</span>
          </p>
        </div>

        <el-table
          :data="currentSignResult.details"
          border
          size="mini"
          class="result-table"
        >
          <el-table-column prop="id" label="序号" width="60" align="center"></el-table-column>
          <el-table-column prop="name" label="姓名" width="100" align="center"></el-table-column>
          <el-table-column prop="idCard" label="证件编号" width="180" align="center"></el-table-column>
          <el-table-column prop="phone" label="联系电话" width="130" align="center"></el-table-column>
          <el-table-column prop="signTime" label="签到时间" width="160" align="center"></el-table-column>
          <el-table-column prop="status" label="状态" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.status === '已签到' ? 'success' : 'danger'">
                {{ scope.row.status }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="remark" label="备注" align="left"></el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="resultVisible = false">关闭</el-button>
          <el-button type="primary" @click="exportSignResult">导出结果</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { selectList, addClassCheckin, updateClassCheckin, delClassCheckin } from "@/api/training/ClassCheckin";
import { listByClassId } from "@/api/training/TrainingSchedule";
export default {
  name: 'SignManagement',
  data() {
    return {
      // 培训班基本信息
      classId: '',
      className: '',
      handoverStatus: '',
      trainingClassCode: '',
      // 签到记录数据（从后端获取）
      signRecords: [],
      // 分页信息
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      // 选中的签到记录
      selectedRecords: [],
      // 二维码相关
      qrcodeVisible: false,
      qrcodeUrl: '',
      qrcodeTitle: '',
      qrcodeError: false,
      currentSignRecord: null,
      // 签到结果相关
      resultVisible: false,
      currentSignResult: null,
      // 下一个ID（新增记录用）
      nextId: 1,

      // 培训计划列表（下拉数据源）
      scheduleList: [],
    };
  },
  computed: {
    // 是否有选中的记录
    hasSelection() {
      return this.selectedRecords.length > 0;
    }
  },
  created() {
    this.getList();
    this.getScheduleList();
  },
  watch: {
    '$route.query.classId': {
      immediate: true,
      handler(newId) {
        const params = this.$route.params;
        this.classId = params.classId;
        this.className = params.className;
        this.handoverStatus = params.handoverStatus;
        this.trainingClassCode = params.trainingClassCode;
        // 路由参数变化时重新加载数据
        this.getList();
        this.getScheduleList(); // 同步更新培训计划列表
      }
    }
  },
  methods: {
    // 根据培训计划ID获取培训内容文本
    getTrainingContent(scheduleId) {
      if (!scheduleId) return '';
      const schedule = this.scheduleList.find(item => item.trainingScheduleId === scheduleId);
      return schedule ? schedule.trainingContent : '未知内容';
    },

    async getScheduleList() {
      if (!this.classId) return;

      try {
        const res = await listByClassId(this.classId);
        if (res.code === 200) {
          this.scheduleList = res.rows;
        } else {
          this.$message.error(`获取培训计划失败：${res.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('请求培训计划失败：', error);
        this.$message.error('网络异常，请稍后重试');
      }
    },

    async getList() {
      if (!this.classId) return;

      try {
        const res = await selectList({
          trainingClassId: this.classId,
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize
        });

        if (res.code === 200) {
          this.signRecords = res.rows.map(item => {
            // 拆分开始时间（后端格式：yyyy-MM-dd HH:mm:ss）
            const startParts = item.checkinStartTime ? item.checkinStartTime.split(' ') : ['', ''];
            // 拆分结束时间
            const endParts = item.checkinEndTime ? item.checkinEndTime.split(' ') : ['', ''];

            // 计算状态（当前时间 > 结束时间 → 已结束）
            const currentTime = new Date();
            const endTime = new Date(item.checkinEndTime);
            const status = currentTime > endTime ? '已结束' : '未开始';

            return {
              ...item,
              id: item.classCheckinId, // 后端唯一标识（classCheckinId）
              checkinTime: item.checkinTime || '',
              startTime: startParts[1] || '', // 开始时间（仅时间部分）
              endTime: endParts[1] || '', // 结束时间（仅时间部分）
              trainingScheduleId: item.trainingScheduleId || '', // 培训计划ID
              checkinLocation: item.checkinLocation || '',
              status: status,
              editable: false
            };
          });

          this.pagination.total = res.total || 0;

          // 计算nextId（确保新增记录ID不重复）
          if (this.signRecords.length > 0) {
            const ids = this.signRecords.map(item => Number(item.id));
            this.nextId = Math.max(...ids) + 1;
          } else {
            this.nextId = 1;
          }
        } else {
          this.$message.error(`获取数据失败：${res.msg || '未知错误'}`);
        }
      } catch (error) {
        console.error('请求签到记录失败：', error);
        this.$message.error('网络异常，请稍后重试');
      }
    },

    // 签到详情跳转
    attendanceRecord(row) {
      this.$router.push({
        name: '签到详情',
        params: {
          classCheckinId: row.classCheckinId, // 传递当前签到记录ID
          className: this.className,
          classId: this.classId,
          checkinTime:row.checkinTime,
          checkinLocation:row.checkinLocation,
          trainingClassCode:this.trainingClassCode
        }
      });
    },

    // 签到统计跳转
    attendanceTracking() {
      this.$router.push({
        name: '签到统计',
        params: {
          classId: this.classId,
          className: this.className,
          trainingClassCode: this.trainingClassCode,
        }
      });
    },

    handleSelectionChange(selection) {
      this.selectedRecords = selection;
    },

    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.pagination.currentPage = 1;
      this.getList();
    },

    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.getList();
    },

    handleExport() {
      this.$message.info('签到记录导出功能已触发');
      // 实际调用：window.location.href = `/api/export?trainingClassId=${this.classId}`;
    },

    // 添加新的签到记录
    handleAddSignRecord() {
      const today = new Date().toISOString().split('T')[0];
      this.signRecords.unshift({
        id: `temp_${this.nextId++}`, // 临时ID（后端保存时会替换）
        checkinTime: today,
        startTime: '09:00:00',
        endTime: '11:30:00',
        trainingScheduleId: '', // 培训计划ID（初始为空）
        checkinLocation: '',
        status: '未开始',
        editable: true
      });
      this.pagination.total++;
    },

    // 增加一行空记录
    addEmptyRow() {
      const today = new Date().toISOString().split('T')[0];
      this.signRecords.push({
        id: `temp_${this.nextId++}`,
        checkinTime: today,
        startTime: '',
        endTime: '',
        trainingScheduleId: '',
        checkinLocation: '',
        status: '未开始',
        editable: true
      });
      this.pagination.total++;
    },

    showBatchQrcode() {
      this.qrcodeTitle = '批量签到二维码';
      this.currentSignRecord = null;
      this.qrcodeUrl = `/api/qrcode/batch?trainingClassId=${this.classId}`; // 实际接口地址
      this.qrcodeError = false;
      this.qrcodeVisible = true;
    },

    showSingleQrcode(id) {
      const record = this.signRecords.find(item => item.id === id);
      if (record) {
        this.currentSignRecord = { ...record };
        this.qrcodeTitle = `签到二维码 - ${this.getTrainingContent(record.trainingScheduleId)}`;
        this.qrcodeUrl = `/api/qrcode/single?classCheckinId=${id}`; // 实际接口地址
        this.qrcodeError = false;
        this.qrcodeVisible = true;
      }
    },

    handleQrcodeError() {
      this.qrcodeError = true;
    },

    handlePrintQrcode() {
      this.$message.info('批量二维码打印功能已触发');
      // 实际调用打印接口
    },

    printCurrentQrcode() {
      this.$message.info('当前二维码打印功能已触发');
      // 实际调用打印接口
    },

    exportSignResult() {
      this.$message.info('签到结果导出功能已触发');
      // 实际调用：window.location.href = `/api/export/result?classCheckinId=${this.currentSignResult.id}`;
    },

    // 批量删除
    async handleBatchDelete() {
      this.$confirm('确定要删除选中的签到记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const ids = this.selectedRecords
          .map(item => item.id)
          .filter(id => !id.startsWith('temp_'));
        try {
          this.res()
          if(ids.length !==0){
            await delClassCheckin(ids); // 调用批量删除接口
          }
          this.$message.success('删除成功');
          this.res(); // 重新加载数据
          this.selectedRecords = [];
        } catch (error) {
          console.error('批量删除失败：', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    // 删除单个签到记录
    async deleteSignRecord(id) {
      this.$confirm('确定要删除该签到记录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          this.res()
          if( !id.startsWith('temp_')){
            await delClassCheckin([id]);
          }
          this.$message.success('删除成功');
          this.res(); // 重新加载数据
        } catch (error) {
          console.error('删除失败：', error);
          this.$message.error('删除失败，请稍后重试');
        }
      }).catch(() => {
        this.$message.info('已取消删除');
      });
    },

    enterEditMode(row) {
      row.editable = true;
    },
    res(){
      this.getList();
    this.getScheduleList();
    },

    // 保存签到记录（核心：按后端格式构造参数）
    async saveSignRecord(row) {
      // 验证必填字段
      if (!this.classId) {
        this.$message.warning('培训班ID不存在');
        return;
      }
      if (!row.checkinTime) {
        this.$message.warning('请选择签到日期');
        return;
      }
      if (!row.startTime || !row.endTime) {
        this.$message.warning('请选择开始和结束时间');
        return;
      }
      if (!row.trainingScheduleId) {
        this.$message.warning('请选择培训计划');
        return;
      }
      if (!row.checkinLocation) {
        this.$message.warning('请填写签到地点');
        return;
      }
      // 验证时间逻辑
      if (row.startTime > row.endTime) {
        this.$message.warning('开始时间不能晚于结束时间');
        return;
      }

      try {
        // 构造后端要求的参数格式
        const params = {
          trainingClassId: this.classId, // 培训班ID（必传）
          checkinTime: row.checkinTime, // 签到日期（yyyy-MM-dd）
          checkinStartTime: `${row.checkinTime} ${row.startTime}`, // 开始时间（yyyy-MM-dd HH:mm:ss）
          checkinEndTime: `${row.checkinTime} ${row.endTime}`, // 结束时间（yyyy-MM-dd HH:mm:ss）
          trainingScheduleId: row.trainingScheduleId, // 培训计划ID
          checkinLocation: row.checkinLocation // 签到地点
        };

        // 区分新增和编辑（编辑需传主键classCheckinId）
        if (row.id && !row.id.startsWith('temp_')) { // 排除临时ID
          params.classCheckinId = row.id;
          await updateClassCheckin(params); // 编辑接口
        } else {
          await addClassCheckin(params); // 新增接口
        }

        row.editable = false;
        this.$message.success('保存成功');
        this.res(); // 刷新列表
      } catch (error) {
        console.error('保存失败：', error);
        this.$message.error('保存失败，请稍后重试');
      }
    },

    handleDateChange(row) {
      // 可添加日期范围限制（如不能选择过去的日期）
    },

    handleTimeChange(row) {
      if (row.startTime && row.endTime && row.startTime > row.endTime) {
        this.$message.warning('开始时间不能晚于结束时间');
      }
    }
  }
};
</script>

<style scoped>
.sign-management-container {
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.top-info-bar {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.class-info {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 14px;
}

.info-item {
  color: #606266;
}

.splitter {
  color: #c0c4cc;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 15px;
}
.operation-buttons .el-button { padding: 6px 10px; }

.sign-records-table {
  margin-bottom: 15px;
}

.add-row-btn {
  margin-bottom: 20px;
}

.pagination {
  text-align: right;
  margin-top: 15px;
}

.qrcode-content {
  padding: 10px;
  text-align: center;
}

.qrcode-wrapper {
  margin-bottom: 15px;
}

.qrcode-img {
  width: 200px;
  height: 200px;
  margin: 0 auto;
}

.qrcode-error {
  color: #f56c6c;
  margin-top: 10px;
  font-size: 14px;
}

.qrcode-info {
  text-align: left;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 14px;
}

.qrcode-info p {
  margin: 5px 0;
}

.result-content {
  max-height: 500px;
  overflow-y: auto;
}

.result-header {
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e6e6e6;
}

.result-header h3 {
  margin-bottom: 10px;
  color: #303133;
}

.result-header p {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  font-size: 14px;
}

.result-table {
  width: 100%;
}

.dialog-footer {
  width: 100%;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.operation-btn.success {
  color: #42b983;
}

.operation-btn.danger {
  color: #f56c6c;
}

@media (max-width: 768px) {
  .operation-buttons {
    flex-direction: column;
  }

  .operation-buttons button {
    width: 100%;
  }
}
</style>
